import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Row, Col, Statistic, Tag, message, Modal, Input } from 'antd';
import { CheckCircleOutlined, ClockCircleOutlined, CloseCircleOutlined, CalendarOutlined } from '@ant-design/icons';
import { checkIn, checkOut, getTodayAttendance, applyLeave } from '../../../api/attendance';

const AttendanceRecord = () => {
    const [todayStatus, setTodayStatus] = useState({
        checkIn: null,
        checkOut: null,
        status: 0 // 0-未签到，1-已签到，2-已签退，3-迟到，4-早退，5-缺勤
    });
    const [checkInModalVisible, setCheckInModalVisible] = useState(false);
    const [checkOutModalVisible, setCheckOutModalVisible] = useState(false);
    const [leaveModalVisible, setLeaveModalVisible] = useState(false);
    const [location, setLocation] = useState('');
    const [remark, setRemark] = useState('');
    const [leaveType, setLeaveType] = useState(1);
    const [leaveTime, setLeaveTime] = useState(4);

    useEffect(() => {
        fetchTodayStatus();
    }, []);

    // 获取今日考勤状态
    const fetchTodayStatus = async () => {
        try {
            const response = await getTodayAttendance();
            if (response.data) {
                setTodayStatus({
                    checkIn: response.data.checkIn,
                    checkOut: response.data.checkOut,
                    status: response.data.status
                });
            }
        } catch (error) {
            console.error('获取今日考勤状态失败:', error);
            message.error('获取今日考勤状态失败');
        }
    };

    // 处理签到
    const handleCheckIn = () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    setLocation(`经度: ${position.coords.longitude}, 纬度: ${position.coords.latitude}`);
                    setCheckInModalVisible(true);
                },
                (error) => {
                    console.error('获取位置失败:', error);
                    setLocation('未能获取位置信息');
                    setCheckInModalVisible(true);
                }
            );
        } else {
            setLocation('浏览器不支持获取位置');
            setCheckInModalVisible(true);
        }
    };

    // 提交签到
    const submitCheckIn = async () => {
        try {
            const hide = message.loading('正在签到...', 0);
            await checkIn({ location, remark });
            hide();
            message.success('签到成功');
            setCheckInModalVisible(false);
            setRemark('');
            fetchTodayStatus();
        } catch (error) {
            console.error('签到失败:', error);
            message.error(error.response?.data?.message || '签到失败');
        }
    };

    // 处理签退
    const handleCheckOut = () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    setLocation(`经度: ${position.coords.longitude}, 纬度: ${position.coords.latitude}`);
                    setCheckOutModalVisible(true);
                },
                (error) => {
                    console.error('获取位置失败:', error);
                    setLocation('未能获取位置信息');
                    setCheckOutModalVisible(true);
                }
            );
        } else {
            setLocation('浏览器不支持获取位置');
            setCheckOutModalVisible(true);
        }
    };

    // 提交签退
    const submitCheckOut = async () => {
        try {
            const hide = message.loading('正在签退...', 0);
            await checkOut({ location, remark });
            hide();
            message.success('签退成功');
            setCheckOutModalVisible(false);
            setRemark('');
            fetchTodayStatus();
        } catch (error) {
            console.error('签退失败:', error);
            message.error(error.response?.data?.message || '签退失败');
        }
    };

    // 处理请假
    const handleLeave = () => {
        setLeaveModalVisible(true);
    };

    // 提交请假
    const submitLeave = async () => {
        try {
            const hide = message.loading('正在提交请假申请...', 0);
            const today = new Date();
            const formattedDate = today.toISOString().split('T')[0];
            
            const data = {
                leaveType: leaveType,
                leaveTime: leaveTime,
                startDate: formattedDate,
                endDate: formattedDate,
                reason: remark
            };
            
            await applyLeave(data);
            hide();
            message.success('请假申请提交成功');
            setLeaveModalVisible(false);
            setRemark('');
            setLeaveType(1);
            setLeaveTime(4);
        } catch (error) {
            console.error('请假申请失败:', error);
            message.error(error.response?.data?.message || '请假申请失败');
        }
    };

    return (
        <div className="attendance-record">
            <Row gutter={[16, 16]}>
                <Col span={24}>
                    <Card title="今日考勤" bordered={false}>
                        <Row gutter={[16, 16]} align="middle">
                            <Col span={8}>
                                <Statistic
                                    title="签到状态"
                                    value={todayStatus.status === 0 ? '未签到' : todayStatus.status === 1 ? '已签到' : '已签退'}
                                    valueStyle={{
                                        color: todayStatus.status === 0 ? '#999' : todayStatus.status === 1 ? '#1677ff' : '#52c41a'
                                    }}
                                    prefix={todayStatus.status === 0 ? <ClockCircleOutlined /> : todayStatus.status === 1 ? <CheckCircleOutlined /> : <CheckCircleOutlined />}
                                />
                            </Col>
                            <Col span={8}>
                                <Statistic
                                    title="签到时间"
                                    value={todayStatus.checkIn || '未签到'}
                                    valueStyle={{
                                        color: todayStatus.checkIn ? '#1677ff' : '#999'
                                    }}
                                />
                            </Col>
                            <Col span={8}>
                                <Statistic
                                    title="签退时间"
                                    value={todayStatus.checkOut || '未签退'}
                                    valueStyle={{
                                        color: todayStatus.checkOut ? '#52c41a' : '#999'
                                    }}
                                />
                            </Col>
                        </Row>
                        <Row style={{ marginTop: 24 }}>
                            <Col span={24} style={{ textAlign: 'center' }}>
                                <Space size="large">
                                    <Button 
                                        type="primary" 
                                        icon={<CheckCircleOutlined />} 
                                        size="large"
                                        onClick={handleCheckIn}
                                        disabled={todayStatus.status > 0}
                                    >
                                        签到
                                    </Button>
                                    <Button 
                                        type="primary" 
                                        icon={<CloseCircleOutlined />} 
                                        size="large"
                                        onClick={handleCheckOut}
                                        disabled={todayStatus.status !== 1}
                                    >
                                        签退
                                    </Button>
                                    <Button 
                                        type="default" 
                                        icon={<CalendarOutlined />} 
                                        size="large"
                                        onClick={handleLeave}
                                    >
                                        请假
                                    </Button>
                                </Space>
                            </Col>
                        </Row>
                    </Card>
                </Col>
            </Row>

            {/* 签到弹窗 */}
            <Modal
                title="签到"
                visible={checkInModalVisible}
                onOk={submitCheckIn}
                onCancel={() => setCheckInModalVisible(false)}
            >
                <p>当前位置：{location}</p>
                <Input.TextArea
                    placeholder="请输入备注信息"
                    value={remark}
                    onChange={(e) => setRemark(e.target.value)}
                    rows={4}
                />
            </Modal>

            {/* 签退弹窗 */}
            <Modal
                title="签退"
                visible={checkOutModalVisible}
                onOk={submitCheckOut}
                onCancel={() => setCheckOutModalVisible(false)}
            >
                <p>当前位置：{location}</p>
                <Input.TextArea
                    placeholder="请输入备注信息"
                    value={remark}
                    onChange={(e) => setRemark(e.target.value)}
                    rows={4}
                />
            </Modal>

            {/* 请假弹窗 */}
            <Modal
                title="请假申请"
                visible={leaveModalVisible}
                onOk={submitLeave}
                onCancel={() => setLeaveModalVisible(false)}
            >
                <Space direction="vertical" style={{ width: '100%' }}>
                    <Select
                        value={leaveType}
                        onChange={(value) => setLeaveType(value)}
                        style={{ width: '100%' }}
                    >
                        <Select.Option value={1}>事假</Select.Option>
                        <Select.Option value={2}>病假</Select.Option>
                        <Select.Option value={3}>年假</Select.Option>
                        <Select.Option value={4}>调休</Select.Option>
                    </Select>
                    <Select
                        value={leaveTime}
                        onChange={(value) => setLeaveTime(value)}
                        style={{ width: '100%' }}
                    >
                        <Select.Option value={4}>半天</Select.Option>
                        <Select.Option value={8}>一天</Select.Option>
                    </Select>
                    <Input.TextArea
                        placeholder="请输入请假原因"
                        value={remark}
                        onChange={(e) => setRemark(e.target.value)}
                        rows={4}
                    />
                </Space>
            </Modal>
        </div>
    );
};

export default AttendanceRecord;